package com.wannengbang.cloudleader.shop;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.AliPayDataBean;
import com.wannengbang.cloudleader.bean.PayStatusBean;
import com.wannengbang.cloudleader.bean.ShopPayStatusBean;
import com.wannengbang.cloudleader.bean.WXPayDataBean;
import com.wannengbang.cloudleader.event.OrderRefushEvent;
import com.wannengbang.cloudleader.event.PaySuccessEvent;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.mine.MyOrderListActivity;
import com.wannengbang.cloudleader.pay.alipay.AliPayUtil;
import com.wannengbang.cloudleader.pay.alipay.PayResult;
import com.wannengbang.cloudleader.pay.wxpay.WXPayUtil;
import com.wannengbang.cloudleader.utils.FastClickUtils;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.AppTitleBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopPayOrderActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_wxpay_check)
    ImageView ivWxpayCheck;
    @BindView(R.id.ll_wxpay)
    LinearLayout llWxpay;
    @BindView(R.id.iv_alipay_check)
    ImageView ivAlipayCheck;
    @BindView(R.id.ll_alipay)
    LinearLayout llAlipay;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    //1微信 2支付宝
    private int payMode = 1;
    private String order_no;
    private String totalPrice;
    private IHomePageModel homePageModel;
    private String payPage;
    private Handler mHandler1 = new Handler(Looper.getMainLooper());
    private int count;
    private Runnable mTimeCounterRunnable = new Runnable() {
        @Override
        public void run() {
            count++;
            if (count >= 30) {
                ToastUtil.showShort("支付失败");
                dismissProgress();
                mHandler1.removeCallbacks(mTimeCounterRunnable);
            } else {
                requestOrderPayStatus();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_pay_order);
        ButterKnife.bind(this);
        registerEventBus();
        initView();
    }

    public void initView() {
        homePageModel = new HomePageModelImpl();
        order_no = getIntent().getStringExtra("order_no");
        totalPrice = getIntent().getStringExtra("totalPrice");
        payPage = getIntent().getStringExtra("payPage");
        tvTotalPrice.setText(totalPrice);
        //默认支付宝
        payMode = 2;
        ivWxpayCheck.setImageResource(R.mipmap.ic_order_kongyuan);
        ivAlipayCheck.setImageResource(R.mipmap.ic_order_xuanze);
    }

    @OnClick({R.id.ll_wxpay, R.id.ll_alipay, R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_wxpay:
                payMode = 1;
                ivWxpayCheck.setImageResource(R.mipmap.ic_order_xuanze);
                ivAlipayCheck.setImageResource(R.mipmap.ic_order_kongyuan);
                break;
            case R.id.ll_alipay:
                payMode = 2;
                ivWxpayCheck.setImageResource(R.mipmap.ic_order_kongyuan);
                ivAlipayCheck.setImageResource(R.mipmap.ic_order_xuanze);
                break;
            case R.id.tv_submit:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                requestOrderPay();
                break;
        }
    }

    /**
     * 支付宝支付回调
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            String resultStatus = payResult.getResultStatus();
            super.handleMessage(msg);
            switch (msg.what) {
                case 6:
                    if (TextUtils.equals(resultStatus, "9000")) {
                        requestOrderPayStatus();
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        ToastUtil.showShort("支付取消");
                        finish();
                    } else {
                        ToastUtil.showShort("支付失败");
                        finish();
                    }
                    break;

            }
        }
    };

    @Subscribe
    public void onPaySuccessEvent(PaySuccessEvent event) {
        if (event.getPayStatus() == 0) {
            requestOrderPayStatus();
        } else {
            finish();
        }
    }

    /**
     * 支付
     */
    public void requestOrderPay() {
        showProgress("支付中.....");
        //支付宝支付
        if (payMode == 2) {
            homePageModel.requestIntegralOrderPay(order_no, new DataCallBack<AliPayDataBean>() {
                @Override
                public void onSuccessful(AliPayDataBean bean) {
                    AliPayUtil.payV2(mActivity, bean.getData(), mHandler);
                }

                @Override
                public void onFailed(String msg, String code) {

                }
            });
        }
        //微信支付
        if (payMode == 1) {
            homePageModel.requestIntegralWXOrderPay(order_no, new DataCallBack<WXPayDataBean>() {
                @Override
                public void onSuccessful(WXPayDataBean bean) {
                    WXPayUtil.pay(mActivity, bean);
                }

                @Override
                public void onFailed(String msg, String code) {

                }
            });
        }
    }

    /**
     * 轮询订单
     */
    public void requestOrderPayStatus() {
        homePageModel.requestIntegralOrderPayStatus(order_no, new DataCallBack<ShopPayStatusBean>() {
            @Override
            public void onSuccessful(ShopPayStatusBean bean) {
                if (bean.getData().getOrder_status() == 2) {
                    ToastUtil.showShort("支付成功");
                    EventBus.getDefault().post(new OrderRefushEvent());
                    if (!TextUtils.isEmpty(payPage)) {
                        showActivity(ShopMyOrderListActivity.class);
                    }
                    mHandler1.removeCallbacks(mTimeCounterRunnable);
                    finish();
                } else if (bean.getData().getOrder_status() == 1) {
                    mHandler1.postDelayed(mTimeCounterRunnable, 1 * 1000);
                } else {
                    ToastUtil.showShort("支付失败");
                    dismissProgress();
                    mHandler1.removeCallbacks(mTimeCounterRunnable);
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭定时任务
        mHandler1.removeCallbacks(mTimeCounterRunnable);
    }

    private Dialog progress;

    public void showProgress(String message) {
        if (progress == null) {
            progress = new Dialog(mActivity, R.style.ShowProgressUtils);
        }
        View view = View.inflate(mActivity, R.layout.dialog_view_loading, null);
        TextView textView = view.findViewById(R.id.loadingText);
        textView.setText(message);
        progress.setContentView(view);
        progress.setCanceledOnTouchOutside(false);
        progress.setCancelable(true);
        try {
            progress.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissProgress() {
        if (progress == null) {
            return;
        }
        try {
            progress.dismiss();
            progress = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
